﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using AL.Common;
using AL.Entity;
using STSdb4.Database;

namespace AL.DAL.PublicHistoryPage
{

    /// <summary>
    /// 公众号文章分页数据操作类
    /// </summary>
    public static class Provider
    {

        private static XIndex<string, HistoryPage> _table = null;

        private static readonly string Path = Config.DataPath;
        private const string SystemFileName = "HH_HIstoryPage.sys";
        private const string DataFileName = "HH_HistoryPage.dat";

        private const string DataTableName = "PublicHistoryPage";


        // 防止文件占用
        //private static string _lockStatus = "None";
        private static bool _isWorking = false;

        /// <summary>
        /// HH: 新增一条记录
        /// </summary>
        public static string Add(HistoryPage record)
        {
            //// 如果再出问题就使用 Lock 锁
            //lock (_lockStatus) {
            //    // 需要执行的代码
            //};

            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            var keyId = record.Key;
            if (!string.IsNullOrWhiteSpace(keyId))
            {
                using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
                {
                    _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                    if (_table != null)
                    {
                        _table[record.Key] = record;

                        _table.Flush();
                    }
                    engine.Commit();
                }
            }
            else
            {
                keyId = string.Empty;
            }

            _isWorking = false;
            return keyId;
        }


        /// <summary>
        /// HH: 编辑一条记录
        /// </summary>
        public static void Mod(HistoryPage record)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                _table.Replace(record.Key, record);

                _table.Flush();
                engine.Commit();

                _isWorking = false;
            }
        }


        /// <summary>
        /// HH: 根据主键 ID 删除一条记录
        /// </summary>
        public static void Del(string keyId)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);
                _table.Delete(keyId);
                _table.Flush();
                engine.Commit();

                _isWorking = false;
            }
        }


        /// <summary>
        /// HH: 删除一个 openId 下的所有记录
        /// </summary>
        public static void DelByOpenId(string openId)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);
                var list = _table.Backward().Where(o => o.Value.OpenId == openId);
                foreach (var keyValuePair in list)
                {
                    _table.Delete(keyValuePair.Key);
                }
                _table.Flush();
                engine.Commit();

                _isWorking = false;
            }
        }

        /// <summary>
        /// HH: 删除一个 openId 下 指定 pageIndex 的记录
        /// </summary>
        public static void DelByOpenId(string openId, int pageIndex)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);
                var list = _table.Backward().Where(o => o.Value.OpenId == openId && o.Value.Page == pageIndex);
                foreach (var keyValuePair in list)
                {
                    _table.Delete(keyValuePair.Key);
                }
                _table.Flush();
                engine.Commit();

                _isWorking = false;
            }
        }


        /// <summary>
        /// HH: 删除该表所有数据
        /// </summary>
        public static void Clear()
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);
                _table.Clear();
                _table.Flush();
                engine.Commit();

                _isWorking = false;
            }
        }



        /// <summary>
        /// HH: 根据 ID 获取一个记录对象
        /// </summary>
        public static HistoryPage GetByKeyId(string keyId)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                _isWorking = false;
                return _table.TryGetOrDefault(keyId, new HistoryPage());
            }
        }


        /// <summary>
        /// HH: 根据 OpenID 获取一个记录对象
        /// </summary>
        public static List<HistoryPage> GetByOpenId(string openId)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                var list = _table.Backward().Where(o => o.Value.OpenId == openId);

                var r = new List<HistoryPage> { };
                r.AddRange(list.Select(item => item.Value));

                _isWorking = false;
                return r;
            }
        }

        public static HistoryPage GetByOpenId(string openId, int pageIndex)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                var ret = _table.Backward().FirstOrDefault(o => o.Value.OpenId == openId && o.Value.Page == pageIndex);

                _isWorking = false;
                return ret.Value;
            }
        }


        /// <summary>
        /// HH: 查询获取对象集合
        /// </summary>
        public static List<HistoryPage> Search(List<Func<KeyValuePair<string, HistoryPage>, bool>> predicate, int inPageIndex, int inPageSize, out int outPageCount)
        {
            while (_isWorking == true)
            {
                System.Threading.Thread.Sleep(100);
            }
            _isWorking = true;

            using (var engine = new StorageEngine(Path + SystemFileName, Path + DataFileName))
            {
                _table = engine.OpenXIndex<string, HistoryPage>(DataTableName);

                outPageCount = 0;

                //var list = _table.Backward().Where(predicate);

                // 多条件模式
                //var list = _table.Backward().Where(o => (int)o.Value.OPType == 1);
                var list = _table.Backward();
                foreach (Func<KeyValuePair<string, HistoryPage>, bool> p in predicate)
                {
                    list = list.Where(p);
                }



                if (list != null && list.Count() > 0)
                {

                    // 分页查询
                    int pageSize = inPageSize;
                    int pageIndex = inPageIndex;
                    outPageCount = list.Count();

                    var r = new List<HistoryPage> { };

                    long rowID = 1;
                    long minID = (pageIndex - 1) * pageSize + 1;
                    long maxID = minID + pageSize - 1;

                    // 遍历
                    foreach (KeyValuePair<string, HistoryPage> item in list)
                    {
                        if (rowID >= minID && rowID <= maxID)
                        {
                            r.Add(item.Value);
                        }
                        rowID++;

                        if (rowID == maxID + 1) break;
                    }


                    _isWorking = false;
                    return r;
                }

                _isWorking = false;
                return null;
            }
        }




    }
}
